package com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.useraction;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;

import com.example.dante.a17376060_wanghaikang_finaltest.R;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.adapter.DownloadAdapter;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.adapter.NewsAdapter;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.domain.News;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.downloadaction.DownloadTask;
import com.example.dante.a17376060_wanghaikang_finaltest.cn.example.main.cn.example.downloadaction.Read;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class MyDownLoad extends AppCompatActivity {

    RecyclerView recyclerView;
    private List<News> newsList;
    String path;
    Read read = new Read();
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    recyclerView.addItemDecoration(new DividerItemDecoration(getApplicationContext(), DividerItemDecoration.VERTICAL));
                    DownloadAdapter newsAdapter = new DownloadAdapter(newsList, getApplicationContext());
                    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                    recyclerView.setAdapter(newsAdapter);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_down_load);
        Toolbar toolbar=findViewById(R.id.download_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("我的下载");
        initView();
    }

    private void initView() {
        recyclerView=findViewById(R.id.download_news);
        path = DownloadTask.NEWS_PATH;
        if (path!=null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    okhttp();
                }
            }).start();
        }else{
            Toast.makeText(this,"还没有下载文件",Toast.LENGTH_SHORT).show();
        }
    }

    private void okhttp() {
        read.readTxtFile(path);
        Gson gson=new Gson();
        newsList=gson.fromJson(Read.Json, new TypeToken<List<News>>() {
            }.getType());
            Message msg=new Message();
            msg.what=1;
            handler.sendMessage(msg);
    }
}
